#!/usr/bin/env python3
#-*-coding:utf-8-*-
import os
import sys

def prepare():
	#切换目录至/data
	os.chdir('/data')
	#创建数据目录
	os.makedirs('/data/redis/data', 0755)
	#创建日志目录
	os.makedirs('/data/redis/logs', 0755)
	#创建配置文件目录
	os.makedirs('/usr/local/redis/conf', 0755)

	#安装依赖包
	cmd = "yum install -y gcc gcc-c++"
	os.system(cmd)
	
	#下载redis源码包，默认版本为4.0.6
	cmd = "curl -O http://download.redis.io/releases/redis-4.0.6.tar.gz"
	res = os.system(cmd)
	if res != 0:
		print("源码包下载失败，请重试")
		sys.exit(1)

	#解压
	cmd = "tar -xzvf redis-4.0.6.tar.gz"
	res = os.system(cmd)
	if res != 0:
		print("解压失败，请删除源码包后重试")
		sys.exit(1)

def install():
	#编译安装
	code_path = '/data/redis/redis-4.0.6/'
	install_path = '/usr/local/redis/'
	os.chdir(code_path)
	cmd = "make && make install PREFIX=" + install_path
	res = os.system(cmd)
	if res != 0:
		print("安装失败，请检查错误信息，修复后重新安装")
		sys.exit(1)
	
	#复制配置文件
	cmd = "cp "+code_path+"redis.conf "+install_path+"conf"
	os.system(cmd)

	#修改配置文件
	host_ip = 'ip a | grep "scope global" |  awk -F " " \'{print $2}\'|awk -F "/" \'{print $1}\''
	res = os.popen(host_ip).read().strip("\n")
	old_new_list = [
		'sed -i "s/bind 127.0.0.1/bind {}/g" /usr/local/redis/conf/redis.conf'.format(res),
		'sed -i "s/daemonize no/daemonize yes/g" /usr/local/redis/conf/redis.conf',
		'sed -i "s/dir .\//dir \/data\/redis\/data\//g" /usr/local/redis/conf/redis.conf',
		'sed -i "s#logfile \\"\\"#logfile \\"\/data\/redis\/logs\/redis.log\\"#g" /usr/local/redis/conf/redis.conf',
		'sed -i "s#pidfile \/var\/run\/redis_6379.pid#pidfile \/usr\/local\/redis\/redis_6379.pid#g" /usr/local/redis/conf/redis.conf']
	for cmd in old_new_list:
		os.system(cmd)
    #对启动警告进行优化
    cmd_list = [
        'echo 511 > /proc/sys/net/core/somaxconn',
        'sysctl vm.overcommit_memory=1',
        'echo never > /sys/kernel/mm/transparent_hugepage/enabled']
    for cmd in cmd_list:
        os.system(cmd)


def startup_script():
	f = open("/usr/local/redis/redis.sh", mode="w")
	f.write("""#!/bin/bash
command=$1
host=`ip a | grep "scope global" | awk -F " " '{print $2}'| awk -F "/" '{print $1}'`
port=6379
if [ "$command" == "start" ];then
        /usr/local/redis/bin/redis-server /usr/local/redis/conf/redis.conf &
        echo "已启动RedisServer"
elif [ "$command" == "stop" ];then
        /usr/local/redis/bin/redis-cli -h $host -p $port shutdown
        echo "已关闭RedisServer"
else
        echo "---------请输入start|stop参数来启动或者关闭RedisServer！--------"
fi""")
	f.close()
    #给予执行权限
    os.chmod("/usr/local/redis/redis.sh", 0755)
    
if __name__ == "__main__":
	prepare()
	install()
	startup_script()
	print("redis-4.0.6已安装完成...")
	print("redis安装目录: /usr/local/redis")
	print("redis数据目录: /data/redis/data")
	print("redis日志目录: /data/redis/logs")

